package com.owc.service.impl.admin;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.owc.common.enums.BuyChannelEnum;
import com.owc.common.enums.ExceptionEnum;
import com.owc.common.exception.BadRequestException;
import com.owc.common.tool.BeanUtils;
import com.owc.dao.OrderMapper;
import com.owc.domain.DO.BuyModel;
import com.owc.domain.PageBean;
import com.owc.domain.dto.admin.ExchangeOrderDTO;
import com.owc.domain.dto.admin.WealthDTO;
import com.owc.domain.entity.Exchange;
import com.owc.domain.entity.Order;
import com.owc.domain.entity.User;
import com.owc.domain.vo.admin.ExchangeQueryVo;
import com.owc.domain.vo.admin.ProxyBuyVo;
import com.owc.domain.vo.admin.WealthQueryVo;
import com.owc.filter.content.SecurityContextHolder;
import com.owc.service.admin.WealthService;
import com.owc.service.app.ExchangeService;
import com.owc.service.app.OrderService;
import com.owc.service.app.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
@Slf4j
public class WealthServiceImpl implements WealthService {

    @Resource
    private OrderService orderService;
    @Resource
    private ExchangeService exchangeService;

    @Autowired
    private UserService userService;

    @Override
    public PageBean<WealthDTO> getWealthOrderList(WealthQueryVo wealthQueryVo) {
        PageInfo<Order> pageInfo = orderService.getAllOrderList(wealthQueryVo);
        return PageBean.pageBean(pageInfo.getTotal(), BeanUtils.coventObject(pageInfo.getList(),WealthDTO.class));
    }

    @Override
    public Boolean proxyBuy(ProxyBuyVo proxyBuyVo) {

        User user = userService.selectByPhone(proxyBuyVo.getPhone())
                .orElseThrow(() -> new BadRequestException("Not-exist phone"));

        BuyModel buyModel = BeanUtils.transformFrom(proxyBuyVo, BuyModel.class);
        if(buyModel == null){
            throw new BadRequestException(ExceptionEnum.UNKNOWN_ERR);
        }
        buyModel.setProxyUserId(SecurityContextHolder.getCurrentUserId());
        buyModel.setUserId(user.getId());
        buyModel.setChannel(BuyChannelEnum.PROXY_CHANNEL);

        try {
            orderService.generateOrder(buyModel);
        } catch (Exception e) {
            log.error("代理下单出现异常, exMsg:{}",e.getMessage());
            return false;
        }
        return true;
    }

    @Override
    public PageBean<ExchangeOrderDTO> getExchangeOrderList(ExchangeQueryVo exchangeQueryVo) {
        PageInfo<Exchange> pageInfo = exchangeService.getExchangeOrderList(exchangeQueryVo);
        return PageBean.pageBean(pageInfo.getTotal(),BeanUtils.coventObject(pageInfo.getList(),ExchangeOrderDTO.class));
    }
}
